//
//  HistoryDeviceListVC.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/3/26.
//

import UIKit

class HistoryDeviceListVC: RViewController {

    @IBOutlet weak var tableView: UITableView!
    var selectIndex = CacheManager.manager.getValueForKey(OfflineDeviceIndex) as! Int
    var dataArray = [VTDevice]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.title = "デバイスを選択"
        self.tableView.tableFooterView = UIView.init()
        
        /// 本地已链接数据
        if let history = CacheManager.manager.getValueForKey(HistoryDevice) as? [VTDevice], history.count > 0 {
            
            self.dataArray = history
            self.tableView.reloadData()
            
        }
        
    }

}

extension HistoryDeviceListVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: HistoryDeviceListCellId) as! HistoryDeviceListCell
        cell.deviceName.text = self.dataArray[indexPath.row].advName
        cell.selectIcon.image = UIImage.init(named: indexPath.row == self.selectIndex ? "select" : "disSelect")
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectIndex = indexPath.row
        CacheManager.manager.setValueForKey(OfflineDeviceIndex, indexPath.row as NSCoding)
        RManager.manager.currentHistoryDevice = dataArray[indexPath.row]
        self.tableView.reloadData()
    }
    
}
